<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="标题" prop="acticityTitle">
                <el-input v-model="queryParams.acticityTitle" placeholder="请输入首页标题" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>

            <el-form-item label="弹窗类型" prop="orderStatus">
                <el-select v-model="queryParams.orderStatus" placeholder="请选择弹窗类型">
                    <el-option v-for="dict in dict.type.app_activity_type" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                </el-select>
            </el-form-item>

            <el-form-item label="上架状态" prop="orderStatus">
                <el-select v-model="queryParams.orderStatus" placeholder="请选择上架状态">
                    <el-option v-for="dict in dict.type.general_shelf_status" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                </el-select>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['system:activity:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                    v-hasPermi="['system:activity:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                    v-hasPermi="['system:activity:remove']">删除</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" border :data="activityList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="ID" align="center" prop="id" v-if="true" />
            <el-table-column label="标题" align="center" prop="acticityTitle" />
            <el-table-column label="标题描述" align="center" prop="acticityDescription" />
            <el-table-column label="弹窗类型" align="center" prop="sourceType">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.app_activity_type" :value="scope.row.sourceType" />
                </template>
            </el-table-column>
            <el-table-column label="弹窗图片" align="center" prop="sourceContent">
                <template slot-scope="scope">
                    <image-preview :src="scope.row.sourceContent" :width="100" :height="150" />
                </template>
            </el-table-column>
            <el-table-column label="关联商品ID" align="center" prop="sourceShopId" />
            <el-table-column label="关联网页链接" align="center" prop="sourceLink" />
            <el-table-column label="上架状态" align="center" prop="actionStatus">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.general_shelf_status" :value="scope.row.actionStatus" />
                </template>
            </el-table-column>
            <el-table-column fixed="right" align="center" label="操作" width="250">
                <template slot-scope="scope">
                    <div class="button-container">
                        <div class="button-row">
                            <el-button type="primary" round @click="handleUpdateStatus(scope.row, 2)"
                                v-hasPermi="['system:activity:edit']">上架</el-button>
                            <el-button type="success" round @click="handleUpdateStatus(scope.row, 3)"
                                v-hasPermi="['system:activity:edit']">下架</el-button>
                        </div>
                        <div class="button-row">
                            <el-button type="info" round @click="handleUpdate(scope.row)"
                                v-hasPermi="['system:activity:edit']">修改</el-button>
                            <el-button type="danger" round @click="handleDelete(scope.row)"
                                v-hasPermi="['system:activity:remove']">删除</el-button>
                        </div>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />

        <!-- 添加或修改App弹窗信息对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
            <el-form ref="form" label-position="left" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="标题" prop="acticityTitle">
                    <el-input v-model="form.acticityTitle" placeholder="请输入标题" />
                </el-form-item>
                <el-form-item label="标题描述" prop="acticityDescription">
                    <el-input v-model="form.acticityDescription" placeholder="请输入标题描述" />
                </el-form-item>
                <el-form-item label="弹窗类型" prop="sourceType">
                    <el-radio-group v-model="form.sourceType">
                        <el-radio :label=1>图片</el-radio>
                        <el-radio :label=2>商品</el-radio>
                        <el-radio :label=3>网站链接</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item v-if="form.sourceType != 2" label="图片上传" required>
                    <el-upload class="avatar-uploader" accept=".jpg" ref='upload' :limit="1" :headers="upload.headers"
                        :action="upload.url" :on-success='handleFileSuccess' :before-upload="beforeUpload"
                        :auto-upload="true" :data="form">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item v-if="form.sourceType == 2" label="商品ID" prop="sourceShopId">
                    <el-input v-model="form.sourceShopId" placeholder="请输入商品ID" />
                </el-form-item>
                <el-form-item v-if="form.sourceType == 3" label="网站链接" prop="sourceLink">
                    <el-input v-model="form.sourceLink" placeholder="请输入网站链接" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>
  
<script>
import { getToken } from "@/utils/auth";
import { listActivity, getActivity, delActivity, addActivity, updateActivity, updateActivityStatus } from "@/api/activity/data";
export default {
    name: "Activity",
    dicts: ['app_activity_type', 'general_shelf_status'],
    data() {
        return {
            // 按钮loading
            buttonLoading: false,
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // App弹窗信息表格数据
            activityList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                acticityTitle: undefined,
                acticityDescription: undefined,
                sourceType: undefined,
                sourceContent: undefined,
                sourceShopId: undefined,
                sourceLink: undefined,
                actionStatus: undefined,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                id: [
                    { required: true, message: "ID不能为空", trigger: "blur" }
                ],
                acticityTitle: [
                    { required: true, message: "标题不能为空", trigger: "blur" }
                ],
                acticityDescription: [
                    { required: true, message: "标题描述不能为空", trigger: "blur" }
                ],
                sourceType: [
                    { required: true, message: "弹窗类型不能为空", trigger: "change" }
                ],
                sourceContent: [
                    { required: true, message: "图片/网页：图片内容不能为空", trigger: "blur" }
                ],
                sourceShopId: [
                    { required: true, message: "商品：商品ID不能为空", trigger: "blur" }
                ],
                sourceLink: [
                    { required: true, message: "网页：网页链接不能为空", trigger: "blur" }
                ],
            },
            upload: {
                headers: { Authorization: "Bearer " + getToken() },
                url: process.env.VUE_APP_BASE_API + "/vehicle/img/upload",
            },
            fileaddress: null,
            imageUrl: null
        };
    },
    created() {
        this.getList();
    },
    methods: {
        /** 查询App弹窗信息列表 */
        getList() {
            this.loading = true;
            listActivity(this.queryParams).then(response => {
                this.activityList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: undefined,
                acticityTitle: undefined,
                acticityDescription: undefined,
                sourceType: undefined,
                sourceContent: undefined,
                sourceShopId: undefined,
                sourceLink: undefined,
                actionStatus: undefined,
                createBy: undefined,
                updateBy: undefined,
                createTime: undefined,
                updateTime: undefined
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加App弹窗信息";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.loading = true;
            this.reset();
            const id = row.id || this.ids
            getActivity(id).then(response => {
                this.loading = false;
                this.form = response.data;
                this.imageUrl = response.data.sourceContent;
                this.open = true;
                this.title = "修改App弹窗信息";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    this.buttonLoading = true;
                    this.form.sourceContent = this.fileaddress;
                    if (this.form.id != null) {
                        updateActivity(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        }).finally(() => {
                            this.buttonLoading = false;
                        });
                    } else {
                        this.form.actionStatus = 1;
                        addActivity(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        }).finally(() => {
                            this.buttonLoading = false;
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal.confirm('是否确认删除App弹窗信息编号为"' + ids + '"的数据项？').then(() => {
                this.loading = true;
                return delActivity(ids);
            }).then(() => {
                this.loading = false;
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {
            }).finally(() => {
                this.loading = false;
            });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('system/activity/export', {
                ...this.queryParams
            }, `activity_${new Date().getTime()}.xlsx`)
        },

        // 下面是图片上传功能
        handleFileSuccess(response, file) {
            this.fileaddress = response;
            this.imageUrl = URL.createObjectURL(file.raw);// 将上传成功后的图片URL赋值给imageUrl
        },

        //图片格式校验判断
        beforeUpload(file) {
            // 校验文件类型为图片
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传车辆图片大小不能超过2M!');
            }
            return isJPG && isLt2M;
        },

        handleUpdateStatus(row, val) {
            var data = {};
            data.id = row.id;
            data.actionStatus = val;
            updateActivityStatus(data).then(res => {
                this.$modal.msgSuccess("修改成功");
                this.getList();
            }).finally(() => {
                this.loading = false;
            });

        }
    }
};
</script>
<style>
.button-container {
    display: flex;
    flex-direction: column;
}

.button-row {
    display: flex;
    justify-content: center;
    margin-bottom: 10px;
    /* 添加底部间隙，可以根据需要进行调整 */
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 248px;
    display: block;
}
</style>
  